package com.itheima.netty.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {

    private int port;

    private String ip;

    public Client(String ip, int port) {
        this.port = port;
        this.ip = ip;
    }

    /**
     * 客户端连接程序
     */
    public void connect(){
        //1. 定义线程池
        EventLoopGroup worker = new NioEventLoopGroup();
        //2.定义启动类
        Bootstrap bootstrap = new Bootstrap();
        //3.配置启动类属性
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                });
        //4.注册处理程序
        ChannelFuture channelFuture = bootstrap.connect(ip, port);
        channelFuture.channel().closeFuture();
        //5.连接服务器
    }

    public static void main(String[] args) {
        //启动客户端
        new Client("127.0.0.1",10010).connect();
    }

}
